<template>
	<view class="wrap" v-if="popup_show">
		<view class="popup-bg">
			<view class="popup-content" :class="{'popup-content-show' : popup_show}">
				<view class="update-wrap">
					<image src="./images/img.png" class="top-img"></image>
					<view class="content">
						<text class="title">发现新版本V{{ version }}</text>
						<!-- 升级描述 -->
						<view class="title-sub" v-for="(value,key) in note" :key="key">{{ value }}</view>
						<!-- 升级按钮 -->
						<button class="btn" v-if="downstatus < 1" @click="nowUpdate()">立即升级</button>
						<!-- 下载进度 -->
						<view class="sche-wrap" v-else>
							<!-- 更新包下载中 -->
							<view class="sche-bg">
								<view class="sche-bg-jindu" :style="lengthWidth"></view>
							</view>
							<text class="down-text">
								下载进度:{{ (downSize / 1024 / 1024).toFixed(2) }}M/{{ (fileSize / 1024 / 1024).toFixed(2) }}M
							</text>
						</view>
					</view>
				</view>
				<image src="./images/close.png" class="close-ioc" @click="closeUpdate()"></image>
			</view>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import {
		ref,
		reactive,
		toRefs,
		inject,
		computed,
		defineProps
	} from 'vue';
	import {
		onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	onShow(() => {})

	defineOptions({
		name: 'app-update'
	});

	const state = reactive({
		themeColor: JSON.parse(cache.get('themeColor')),
		force: false, //@是否强制更新
		popup_show: false, //弹窗是否显示
		platform: '', //ios or android
		version: '1.0.0', //当前软件版本
		need_update: false, // 是否更新
		downing: false, //是否下载中
		downstatus: 0, //0未下载  1已开始 2已连接到资源  3已接收到数据  4下载完成
		note: [],
		download_url: '',
		full_update: false,
		fileSize: 0, //文件大小
		downSize: 0, //已下载大小
		viewObj: null, //原生遮罩view,
	});

	const props = defineProps({
		tabbar: {
			type: Boolean,
			default: () => false
		}
	})

	const lengthWidth = computed(() => {
		let w = state.downSize / state.fileSize * 100
		if (!w) {
			w = 0
		} else {
			w = w.toFixed(2)
		}
		return {
			width: w + '%' //return 宽度半分比
		}
	});

	// 检查更新
	function update() {
		// #ifdef APP-PLUS
		// 获取手机系统信息
		uni.getSystemInfo({
			success: (res) => {
				if (res.platform == 'android') {
					plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { //获取版本号
						getUpdateInfo(wgtinfo.version)
					})
				}
			}
		})
		// #endif
	}

	// 获取线上版本信息
	function getUpdateInfo(version) {
		//向后台发起请求，获取最新版本号
		let pages = getCurrentPages() // 获取栈实例
		let currentRoute = pages[pages.length - 1].route;
		request.post('index/getAppVersion', {
			version: version
		}).then(res => {
			if (res.code === 1) {
				state.force = res.data.force
				state.full_update = res.data.full_update
				state.version = res.data.new_version
				state.note = res.data.update_text.split('|')
				state.download_url = res.data.download_url
				if (res.data.isUpdate && !state.tabbar && currentRoute == 'pages/tabbar/index/index') {
					if (!/\.wgt$/i.test(state.download_url)) {
						state.viewObj = new plus.nativeObj.View('viewObj', {
							bottom: '0px',
							left: '0px',
							height: '50px',
							width: '100%',
							backgroundColor: 'rgba(0,0,0,.6)'
						})
						state.viewObj.show() //显示原生遮罩
					}
				}
				if (res.data.isUpdate && currentRoute != 'pages/index/index' && !state.tabbar) {
					state.popup_show = false //关闭升级弹窗
					if (state.viewObj) state.viewObj.hide() //隐藏原生遮罩
				}

				if (/\.wgt$/i.test(state.download_url)) {
					state.popup_show = false;
					nowUpdate();
				} else {
					state.popup_show = true;
				}
			}
		})
	}

	// 取消更新
	function closeUpdate() {
		if (state.downstatus > 0) {
			return
		}
		if (state.force) {
			// 强制更新，取消退出app
			plus.os.name == 'Android' ? plus.runtime.quit() : plus.ios.import('UIApplication').sharedApplication()
				.performSelector(
					'exit')
		} else {
			state.popup_show = false //关闭升级弹窗
			if (state.viewObj) state.viewObj.hide() //隐藏原生遮罩
		}
	}

	// 立即更新
	function nowUpdate() {
		if (state.downing) return false //如果正在下载就停止操作
		state.downing = true //状态改变 正在下载中
		download()
	}

	// 下载
	function download() {
		state.downstatus = 1
		let dtask = plus.downloader.createDownload(state.download_url, {
			filename: '_downloads/update/'
		}, (d, status) => {})
		dtask.addEventListener('statechanged', (task, status) => {
			if (status === null) {} else if (status == 200) {
				//在这里打印会不停的执行，请注意，正式上线切记不要在这里打印东西///////////////////////////////////////////////////
				state.downstatus = task.state
				switch (task.state) {
					case 3: // 已接收到数据
						state.downSize = task.downloadedSize
						if (task.totalSize) {
							state.fileSize = task.totalSize //服务器须返回正确的content-length才会有长度
						}
						break
					case 4:
						install(task.filename)
						break
				}
			} else {
				plus.nativeUI.closeWaiting()
				plus.nativeUI.toast('下载出错')
				state.downing = false
				state.downstatus = 0
			}
		})
		dtask.start()
	}

	// 安装
	function install(path) {
		if (state.full_update) {
			plus.runtime.openFile(path)
		} else {
			plus.runtime.install(path, {}, function() {
				plus.nativeUI.closeWaiting()
				// 应用资源下载完成！
				plus.runtime.restart()
				deleteUpdateFile(path)
			}, function(e) {
				plus.nativeUI.closeWaiting()
				// 安装更新文件失败
				deleteUpdateFile(path)
				plus.nativeUI.alert('更新失败')
				plus.runtime.restart()
			})
		}
	}

	// 删除更新文件
	function deleteUpdateFile(path) {
		if (!path) {
			return
		}
		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			// 可通过entry对象操
			if (entry.isFile) {
				entry.remove()
			}
		}, function(e) {})
	}

	function show() {
		update()
	}

	function hide() {
		if (state.viewObj) state.viewObj.hide() //隐藏原生遮罩
	}

	const {
		themeColor,
		force,
		popup_show,
		platform,
		version,
		need_update,
		downing,
		downstatus,
		note,
		download_url,
		full_update,
		fileSize,
		downSize,
		viewObj,
	} = toRefs(state);
</script>

<style lang="scss" scoped>
	.popup-bg {
		z-index: 9999;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		position: fixed;
		top: 0;
		left: 0rpx;
		right: 0;
		bottom: 0;
		width: 750rpx;
		background-color: rgba(0, 0, 0, .6);
	}

	.popup-content {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.popup-content-show {
		animation: mymove 500ms;
		transform: scale(1);
	}

	@keyframes mymove {
		0% {
			transform: scale(0);
			/*开始为原始大小*/
		}

		100% {
			transform: scale(1);
		}

	}


	.update-wrap {
		width: 580rpx;
		border-radius: 18rpx;
		position: relative;
		display: flex;
		flex-direction: column;
		background-color: #ffffff;
		padding: 170rpx 30rpx 0;

		.top-img {
			position: absolute;
			left: 0;
			width: 100%;
			height: 256rpx;
			top: -128rpx;
		}

		.content {
			margin-top: 0;
			display: flex;
			flex-direction: column;
			align-items: center;
			padding-bottom: 40rpx;

			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: rgba(248, 87, 0, 0.87);
			}

			.title-sub {
				text-align: center;
				font-size: 24rpx;
				color: #666666;
				line-height: 42rpx;
			}

			.btn {
				width: 460rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #ffffff;
				font-size: 30rpx;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 100px;
				background-color: rgba(248, 87, 0, 0.87);
				margin-top: 20rpx;
			}
		}
	}


	.close-ioc {
		width: 70rpx;
		height: 70rpx;
		margin-top: 30rpx;
	}

	.sche-wrap {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-end;
		padding: 10rpx 50rpx 0;

		.sche-wrap-text {
			font-size: 24rpx;
			color: #666;
			margin-bottom: 20rpx;
		}

		.sche-bg {
			position: relative;
			background-color: #cccccc;
			height: 30rpx;
			border-radius: 100px;
			width: 480rpx;
			display: flex;
			align-items: center;

			.sche-bg-jindu {
				position: absolute;
				left: 0;
				top: 0;
				height: 30rpx;
				min-width: 40rpx;
				border-radius: 100px;
				background: url(images/round.png) #5775e7 center right 4rpx no-repeat;
				background-size: 26rpx 26rpx;
			}
		}

		.down-text {
			font-size: 24rpx;
			color: #5674e5;
			margin-top: 16rpx;
		}
	}
</style>